package order.service;

import lombok.extern.slf4j.Slf4j;
import order.config.DelayOrderConfiguration;
import order.dao.OrderDao;
import order.entity.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ProducerService {
    /**
     * 注⼊RabbitTemplate
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 注⼊OrderDao
     */
    @Autowired
    private OrderDao orderDao;

    /**
     * 发送消息
     *
     * @param order     订单对象
     * @param delayTime 延迟消费时⻓
     */
    public void createOrder(Order order, int delayTime) {
        //创建消息的唯⼀ID
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(order.getOrderId());
        //将订单信息⼊库，此时订单状态1，表示未⽀付
        orderDao.saveOrder(order);
        log.info("订单已经创建，1分钟内要支付");
        //发送消息
        rabbitTemplate.convertAndSend(DelayOrderConfiguration.DELAY_EXCHANGE_NAME,
                DelayOrderConfiguration.DELAY_ROUTING_NAME, order,
                message -> {
                    //设置延迟时间
                    message.getMessageProperties().setDelay(delayTime);
                    return message;
                }, correlationData);
    }

    public Order getOrderById(String id){
        return orderDao.getOrderById(id);
    }

    public void updateOrder(Order order) {
        orderDao.updateOrder(order);
    }
}
